package com.renovate.imtest;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/1/12.
 * 基础的缓存集合管理模板
 */
public abstract class BaseListCache<T> extends BaseCache<T> {
    protected List<T> mList = new ArrayList<>();

    protected BaseListCache() {
        getList();
    }

    /**
     * 获取信息集合
     */
    public List<T> getList() {
        if (mList == null || mList.isEmpty()) {
            List<T> entrys = dbUtil.selectAll(getThisClass());
            if (entrys != null) {
                mList = entrys;
            } else {
                if (mList == null)
                    mList = new ArrayList<>();
                mList.clear();
            }
        }
        return mList;
    }

    /**
     * 获取信息集合
     */
    public List<T> getList(DataResponse response) {
        getList();
        if (mList.isEmpty()) {
            asyncGetList(response);
        } else
            response.onSuccess();
        return mList;
    }

    public void asyncGetList(DataResponse response) {
    }

    /**
     * 缓存信息集合
     *
     * @param entrys     信息集合
     * @param replaceAll 是否强制执行缓存刷新
     */
    public void setList(List<T> entrys, boolean replaceAll) {
        if (replaceAll) {
            if (entrys == null) {
                mList.clear();
            } else {
                mList = entrys;
            }
            saveList();
        } else {
            setList(entrys);
        }
    }

    /**
     * 保存信息，写入数据库
     */
    public void saveList() {
        dbUtil.clearTable(getThisClass());
        dbUtil.run(new Runnable() {
            @Override
            public void run() {
                dbUtil.saveBindingId(mList);
            }
        });
    }

    /**
     * 更新指定内容
     */
    public void updateList(final T entry) {
        dbUtil.replace(entry);
    }

    /**
     * 将指定内容加入缓存
     */
    public void addToCacheList(final T entry) {
        if (entry == null)
            return;
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).equals(entry)) {
                dbUtil.saveOrUpdate(entry);
                return;
            }
        }
        mList.add(entry);
        dbUtil.saveOrUpdate(entry);
    }

    /**
     * 将指定更新缓存
     */
    public void setList(List<T> entrys) {
        if (mList == null) {
            getList();
        }
        if (entrys != null) {
            mList.addAll(entrys);
            saveList();
        }
    }

    public void clearCache() {
        dbUtil.clearTable(getThisClass());
        mList.clear();
    }

    public interface DataResponse {
        void onSuccess();

        void onResponse(Object object);

        void onError(Object error);
    }
}
